import pandas as pd
import matplotlib.pyplot as plt
import okx.MarketData as MarketData


flag = "0"
marketDataAPI =  MarketData.MarketAPI(flag=flag)
result = marketDataAPI.get_candlesticks(instId="BTC-USDT",bar = '1H')
raw_data = result["data"]

# Step 1. 转为DataFrame，处理时间和收盘价
df = pd.DataFrame(raw_data, columns=[
    'timestamp', 'open', 'high', 'low', 'close', 'vol', 'volCcy', 'volCcyQuote', 'confirm'
])

df['Date'] = pd.to_datetime(df['timestamp'].astype(int), unit='ms')
df.set_index('Date', inplace=True)
df['close'] = df['close'].astype(float)

# 时间升序排列
df = df.sort_index()

# Step 2. 计算MACD相关量（可用默认参数12，26，9）
# ema12和ema26
df['ema12'] = df['close'].ewm(span=12, adjust=False).mean()
df['ema26'] = df['close'].ewm(span=26, adjust=False).mean()
df['dif'] = df['ema12'] - df['ema26']
df['dea'] = df['dif'].ewm(span=9, adjust=False).mean()
df['macd'] = 2 * (df['dif'] - df['dea'])   # MACD柱子，常见实现

# Step 3. 绘制并保存图片
plt.figure(figsize=(10,6))
plt.plot(df.index, df['dif'], label='DIF', color='blue')
plt.plot(df.index, df['dea'], label='DEA', color='orange')
plt.bar(df.index, df['macd'], color=['green' if v>=0 else 'red' for v in df['macd']], label='MACD', width=0.02)

plt.legend()
plt.title('MACD Indicator')
plt.xlabel('Time')
plt.ylabel('MACD')
plt.xticks(rotation=30)
plt.tight_layout()
plt.savefig('crypto_macd.png')
plt.close()
print('MACD图已保存为 crypto_macd.png')
